import {
  HttpException,
  HttpStatus,
  Injectable,
  ServiceUnavailableException,
} from '@nestjs/common';
import { CreateFavDto } from '../dto/fav/create-fav';
import { InjectRepository } from '@nestjs/typeorm';
import { FavEntity } from '../entities/fav.entity';
import { Repository } from 'typeorm';
import { GoodsService } from 'src/module/grocery/service/goods.service';
import { UserService } from './user.service';

@Injectable()
export class FavService {
  constructor(
    @InjectRepository(FavEntity, 'shop')
    private readonly favRepository: Repository<FavEntity>,

    private goodsService: GoodsService,
    private userService: UserService,
  ) {}

  async create(userId: number, productId: number) {
    try {
      const user = await this.userService.findOne(userId);
      const product = await this.goodsService.findOne(productId);
      if (!user || !product) {
        throw new HttpException(
          '用户信息或产品信息不存在',
          HttpStatus.BAD_REQUEST,
        );
      }
      const productFav = new FavEntity({ user, product });
      const result = await this.favRepository.save(productFav);
      if (result) {
        return '收藏成功';
      }
      return '收藏失败';
    } catch (e) {
      throw new ServiceUnavailableException(e);
    }
  }

  async findAll(userId: number, pageDto: { pageNo: number; pageSize: number }) {
    try {
      const result = await this.favRepository.find({
        where: { user: { id: userId } },
        relations: ['product'],
        skip: (pageDto.pageNo - 1) * pageDto.pageSize,
        take: pageDto.pageSize,
      });

      // return {
      //   list,
      //   total,
      //   ...pageDto,
      // };
      return result || []
    } catch (e) {
      throw new ServiceUnavailableException();
    }
  }

  async findOne(id: number) {
    try {
      const res = await this.favRepository.findOneBy({ id });
      return res;
    } catch (e) {
      throw new ServiceUnavailableException();
    }
  }

  async remove(id: number) {
    try {
      const { affected } = await this.favRepository.delete({ id });
      if (affected) {
        return '取消收藏';
      }
      return '取消收藏失败';
    } catch (e) {
      throw new ServiceUnavailableException();
    }
  }
}
